×
☰ See All Chapters

Java BiFunction Functional Interface

BiFunction is the java provided functional interface to perform the desired operation on the values and return the result. . Bi means two, BiFunction works on two values.

Writing an application involves comparing, computing and consuming values. Assume, inside a method say myMeth(), if we have to execute same code multiple time then we have to duplicate the code. To avoid this we can create some utility class and create the method to execute repeated code and call this method inside our method myMeth() any number of times. This is good solution if the common method we wrote is used across the application many times. If we call this utility method only few times inside one particular method, writing a utility class and a utility method is again a bad solution, because, this utility method is sure to be called only few times and that too only when the myMeth()is called. The next solution is to write some functional interface with a method taking desired number of parameters, perform desired operation and return the result. So now, we can use this functional interface with lambda expression and we can execute any logic and use it any times.

BiFunction is the java provided functional interface with two parameters and we do not need to create the functional interface to perform the desired operation on the values and return the result. Just write the logic using lambda expression and use it.

BiFunction Method signature

BiFunction functional method has two parameters and does not return the function result.

@FunctionalInterface

public interface BiFunction<T, U, R> {

    /**

     * Applies this function to the given arguments.

     *

     * @param t the first function argument

     * @param u the second function argument

     * @return the function result

     */

    R apply(T t, U u);

… …

… …

}

BiFunction Example

package com.java4coding;

 

import java.util.function.BiFunction;

 

public class BiFunctionExample {

 

        public static void main(String args[]) {

 

        BiFunction<Integer, Integer, String> biFunction = (num1, num2) -> "Total:" +(num1 + num2);

        System.out.println(biFunction.apply(1,2));

        System.out.println(biFunction.apply(3,9));

        System.out.println(biFunction.apply(5,9));

        }

}

Output:

Total:3

Total:12

Total:14


All Chapters
Author